package com.zhanvie.test;

import com.zhanvie.thread.Main1;
import com.zhanvie.singleton.QueueManager;
import com.zhanvie.thread.CustomThreadFactory;
import com.zhanvie.thread.ExtendRejectHandler;
import com.zhanvie.thread.ExtendThreadPool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    private static final Logger logger = LogManager.getLogger(Main1.class);

    public static void main(String[] args) {
        // 用于竞争资源的锁
        Semaphore semaphore = new Semaphore(3);
        Random random = new Random();

        ExtendThreadPool poolExecutor = new ExtendThreadPool(5, 5,
                QueueManager.getInstance().getThreadQueue(),
                new CustomThreadFactory("lock"),
                new ExtendRejectHandler(50));
        for (int i = 0; i < 10; i++) {
            final int FID = i + 1;
            poolExecutor.submit(()->{
                try {
                    semaphore.acquire();
                    logger.info("车牌号【{}】的车进入停车场", FID);
                    int tingliu = random.nextInt(7);
                    TimeUnit.SECONDS.sleep(tingliu);
                    logger.info("车牌号【{}】的车正在缴停车费", FID);
                    int jiaofei = random.nextInt(2);
                    TimeUnit.SECONDS.sleep(jiaofei);
                } catch (InterruptedException e) {
                    logger.info("车牌号【{}】的车被拦截了，没有进入停车场", FID);
                } finally {
                    logger.info("车牌号【{}】的车已经离开停车场", FID);
                    semaphore.release();
                    System.out.println();
                }
            });
        }
        poolExecutor.shutdown();
    }

}
